<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    /**
     * 获取分类列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_category(){
        $category = DB::table('category')
            ->where('hidden', 0)
            ->get();

        $data = $this->generateTree($category,0,0);
        //子分类
        foreach ($category as $val){
            if ($val->parent_id !== 0){
                $parent = DB::table('category')
                    ->where('id', $val->parent_id)
                    ->first();
                $val->parent_name = $parent->text;
            }else{
                $val->parent_name = '顶级分类';
            }
            $val->created_at = date('Y-m-d H:i:s',$val->created_at);
            $val->is_recommand ? $val->is_recommand = '是' : $val->is_recommand = '否' ;
        }
        return JsonResponse(200,true,'获取成功',$data);
    }

    /**
     * 递归无限极分类
     * @param $items
     * @param $id
     * @param $step
     * @return array
     */
    private function generateTree($items, $id, $step){
        static $tree=[];
        foreach($items as $key=>$val) {
            if($val->parent_id == $id) {
                $flg = str_repeat('―',$step*2);
                $val->text = $flg.$val->text;
                $tree[] = $val;
                $this->generateTree($items , $val->id ,$step+1);
            }
        }
        return $tree;
    }

    public function add(Request $request){
        $insert = $request->post();
        $insert['created_at'] = time();
        $insert['updated_at'] = time();
        $result = DB::table('category')
            ->insert($insert);
        if ($result){
            return JsonResponse(200,true,'添加成功');
        }else{
            return JsonResponse(3001,false,'添加失败，请稍后重试');
        }
    }
}
